<template>
  <div style="height: 91vh; width: 100%; overflow: hidden; display: flex; padding: 15px; background-color: #f0f2f5;">
    <!-- 左侧区域，占比3份 -->
    <div style="flex: 2; display: flex; flex-direction: column; min-width: 0;">
      <!-- 上部分，占比1 - 调用量显示 -->
      <div style="flex: 1; display: flex; margin-bottom: 15px; height: 12vh;">
        <!-- 调用量卡片 -->
        <div class="stat-card stat-card-1">
          <div class="stat-label">今日调用量</div>
          <div class="stat-value">{{ formatNumber(todayCount) }}</div>
          <div class="stat-icon">📊</div>
        </div>
        <div class="stat-card stat-card-2">
          <div class="stat-label">本周调用量</div>
          <div class="stat-value">{{ formatNumber(thisWeekCount) }}</div>
          <div class="stat-icon">📈</div>
        </div>
        <div class="stat-card stat-card-3">
          <div class="stat-label">本月调用量</div>
          <div class="stat-value">{{ formatNumber(thisMonthCount) }}</div>
          <div class="stat-icon">🚀</div>
        </div>
      </div>

      <!-- 中部分，占比3 - 日调用趋势图 -->
      <div class="chart-card" style="flex: 3; margin-bottom: 15px; height: 34vh;">
        <div class="card-header">
          <h3 class="card-title">日调用趋势图</h3>
          <div>
            <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
              <el-radio-button label="7">近7天</el-radio-button>
              <el-radio-button label="15">近15天</el-radio-button>
              <el-radio-button label="30">近一个月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div class="chart-container">
          <div id="trendChart" style="height: 100%;"></div>
        </div>
      </div>

      <!-- 下部分，占比4 - 调用分布和TOP10 -->
      <div style="flex: 4; display: flex; min-width: 0;">
        <!-- 调用分布 -->
        <div class="chart-card" style="flex: 1; margin-right: 15px; min-width: 0; width: 0;">
          <div class="card-header">
            <h3 class="card-title">调用分布</h3>
          </div>
          <div class="chart-container-responsive">
            <div id="distributionChart"></div>
          </div>
        </div>
        <!-- 操作人员排行TOP10 -->
        <div class="chart-card" style="flex: 1; min-width: 0; width: 0;">
          <div class="card-header">
            <h3 class="card-title">操作人员TOP10</h3>
          </div>
          <div class="chart-container-responsive">
            <div id="top10Chart"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧区域，占比1份 -->
    <div style="flex: 1; display: flex; flex-direction: column; margin-left: 15px; min-width: 0;">
      <!-- 公告区域 -->
      <div class="table-card" style="flex: 1; margin-bottom: 15px; height: 42vh">
        <div class="card-header">
          <h3 class="card-title">公告</h3>
        </div>
        <el-table
          :data="noticeData"
          height="calc(100% - 45px)"
          border
          :header-cell-style="tableHeaderStyle">
          <el-table-column
            prop="title"
            label="内容">
            <template #default="{row}">
              <div
                class="scrollable-cell"
                :class="{ 'scroll-active': isTextOverflow(row.title) }"
                :key="row.title"
              >
                {{ row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="date"
            label="日期"
            width="100"
            align="center">
          </el-table-column>
        </el-table>
      </div>
      <!-- 功能调用区域 -->
      <div class="table-card" style="flex: 1;height: 42vh">
        <div class="card-header">
          <h3 class="card-title">功能调用</h3>
        </div>
        <el-table
          :data="functionData"
          height="calc(100% - 45px)"
          border
          :header-cell-style="tableHeaderStyle">
          <el-table-column
            prop="name"
            label="功能"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            width="100"
            prop="count"
            label="调用次数"
            align="center">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {getNoticeList} from "@/api/system/notice"
import {getDashboardStats} from "@/api/system/operlog";
export default {
  name: 'Index',
  data() {
    return {
      timeRange: '7',
      trendChart: null,
      distributionChart: null,
      top10Chart: null,
      resizeTimer: null,
      refreshTimer: null, // 自动刷新定时器
      refreshIntervalMinutes: 5, // 自动刷新间隔（分钟）
      // 统计数据
      todayCount: 0,
      thisWeekCount: 0,
      thisMonthCount: 0,
      dailyTrendData: [],
      operatorDistributionData: [],
      moduleCallData: [],
      noticeData: [],
      functionData: [],
      operatorTop10: []
    }
  },
  // 当组件挂载后初始化滚动检查
  mounted() {
    this.getList()
    this.initCharts()
    // 添加窗口大小变化监听事件
    window.addEventListener('resize', this.handleResize)
    // 设置自动刷新定时器
    this.refreshTimer = setInterval(() => {
      this.getList(); // 调用getList()方法刷新所有数据，包括公告
    }, this.refreshIntervalMinutes * 60 * 1000); // 转换为毫秒
  },
  // 监听时间范围变化
  watch: {
    timeRange() {
      this.handleTimeRangeChange()
    }
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose()
    }
    if (this.distributionChart) {
      this.distributionChart.dispose()
    }
    if (this.top10Chart) {
      this.top10Chart.dispose()
    }
    // 移除窗口大小变化监听事件
    window.removeEventListener('resize', this.handleResize)
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer)
    }
    // 清除自动刷新定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  methods: {
    getList() {
      // 加载公告数据
      getNoticeList().then(response => {
        // 处理通知数据
        this.noticeData = response.data.map(item => ({
          // 组合标题和内容，去除HTML标签
          title: `${item.noticeTitle}:${this.removeHtmlTags(item.noticeContent || '')}`,
          // 只取日期部分，去掉时间
          date: item.createTime ? item.createTime.split(' ')[0] : ''
        }));
      });

      // 加载统计数据
      this.loadDashboardStats();
    },

    // 加载仪表盘统计数据
    loadDashboardStats() {
      getDashboardStats({ days: parseInt(this.timeRange) }).then(response => {
        const data = response.data;

        // 更新调用量数据
        this.todayCount = data.todayCount || 0;
        this.thisWeekCount = data.thisWeekCount || 0;
        this.thisMonthCount = data.thisMonthCount || 0;

        // 更新日调用趋势数据
        this.dailyTrendData = data.dailyTrend || [];

        // 更新操作人员分布数据
        this.operatorDistributionData = this.formatOperatorDistribution(data.operatorDistribution || []);

        // 更新系统模块调用数据
        this.moduleCallData = data.moduleCallCount || [];
        this.functionData = this.formatModuleCallData(this.moduleCallData);

        // 更新操作人员TOP10数据
        this.operatorTop10 = data.operatorTop10 || [];

        // 重新渲染图表
        this.updateCharts();
      }).catch(error => {
        console.error('加载统计数据失败:', error);
      });
    },

    // 格式化操作人员分布数据
    formatOperatorDistribution(data) {
      const colors = ['#1976D2', '#4CAF50', '#FF9800', '#E91E63', '#9C27B0', '#00BCD4', '#FF5722', '#607D8B', '#795548', '#3F51B5'];
      return data.slice(0, 8).map((item, index) => ({
        name: item.name || '未知用户',
        value: item.count || 0,
        percentage: item.percentage || 0,
        itemStyle: { color: colors[index % colors.length] }
      }));
    },

    // 格式化系统模块调用数据
      formatModuleCallData(data) {
        return data.slice(0, 10).map(item => ({
          name: item.module || '未知模块',
          count: item.count || 0
        }));
      },

      // 格式化数字，添加千分位分隔符
      formatNumber(num) {
        if (num === null || num === undefined) {
          return '0';
        }
        return Number(num).toLocaleString('zh-CN');
      },

    // 更新所有图表
    updateCharts() {
      if (this.trendChart) {
        this.updateTrendChart();
      }
      if (this.distributionChart) {
        this.updateDistributionChart();
      }
      if (this.top10Chart) {
        this.updateTop10Chart();
      }
    },

    // 去除HTML标签的方法
    removeHtmlTags(html) {
      return html.replace(/<[^>]*>/g, '');
    },

    initCharts() {
      this.initTrendChart()
      this.initDistributionChart()
      this.initTop10Chart()
    },
    initTrendChart() {
      const chartDom = document.getElementById('trendChart')
      if (!chartDom) return

      this.trendChart = echarts.init(chartDom)
      this.updateTrendChart();
    },

    // 更新趋势图
    updateTrendChart() {
      const { dates, values } = this.getTrendChartData();

      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e4e7ed',
          borderRadius: 8,
          boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)',
          formatter: (params) => {
            const data = params[0]
            // 显示年份+日期+数据值
            const fullDate = this.getFullDateByShortDate(data.axisValue)
            return `${fullDate}<br/>调用量: ${data.value}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%', // 增加底部空间以更好地显示日期
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#606266',
            fontSize: 12,
            // 旋转日期标签以避免重叠
            rotate: this.timeRange === '30' ? 45 : (this.timeRange === '15' ? 30 : 0)
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f0f2f5',
              type: 'dashed'
            }
          }
        },
        series: [{
          name: '调用量',
          type: 'line',
          smooth: true,
          data: values,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: 'rgba(25, 118, 210, 0.3)'},
              {offset: 1, color: 'rgba(25, 118, 210, 0.05)'}
            ])
          },
          lineStyle: {
            color: '#1976D2',
            width: 3
          },
          itemStyle: {
            color: '#1976D2',
            borderWidth: 2,
            borderColor: '#fff'
          },
          // 在点上显示数据标签
          label: {
            show: true,
            position: 'top',
            color: '#1976D2',
            fontSize: 10,
            formatter: '{c}'
          }
        }]
      }

      this.trendChart.setOption(option)
    },

    // 获取趋势图数据
    getTrendChartData() {
      if (this.dailyTrendData && this.dailyTrendData.length > 0) {
        // 对于后端返回的YYYY-MM-DD格式，x轴显示月-日格式以保持简洁
        const dates = this.dailyTrendData.map(item => {
          const dateStr = item.date || '';
          // 如果是YYYY-MM-DD格式，提取月-日部分显示在x轴上
          if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
            return dateStr.substring(5); // 返回 MM-DD 格式
          }
          return dateStr;
        });
        const values = this.dailyTrendData.map(item => {
          return item.count || 0;
        });
        return { dates, values };
      }
      // 如果没有数据，返回默认数据
      return this.getTimeRangeData();
    },
    initDistributionChart() {
      const chartDom = document.getElementById('distributionChart')
      if (!chartDom) return

      this.distributionChart = echarts.init(chartDom)
      this.updateDistributionChart();
    },

    // 更新分布图
    updateDistributionChart() {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const data = params.data;
            return `${data.name}<br/>操作数: ${data.value}<br/>占比: ${data.percentage || params.percent}%`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e4e7ed',
          borderRadius: 8,
          boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)'
        },
        series: [{
          name: '操作人员分布',
          type: 'pie',
          radius: ['25%', '50%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: (params) => {
              const data = params.data;
              const percentage = data.percentage || params.percent;
              return `${data.name}\n(${percentage}%)`;
            },
            position: 'outer',
            fontSize: 10,
            color: '#606266',
            lineHeight: 16
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold',
              formatter: (params) => {
                const data = params.data;
                const percentage = data.percentage || params.percent;
                return `${data.name}\n操作数: ${data.value}\n占比: ${percentage}%`;
              }
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 8,
            lineStyle: {
              width: 1,
              type: 'solid'
            }
          },
          data: this.operatorDistributionData.length > 0 ? this.operatorDistributionData : this.getEmptyDistributionData()
        }]
      }

      this.distributionChart.setOption(option)
    },

    // 获取空的分布数据
    getEmptyDistributionData() {
      return [
        {value: 1, name: '暂无数据', itemStyle: {color: '#CCCCCC'}}
      ];
    },
    initTop10Chart() {
      const chartDom = document.getElementById('top10Chart')
      if (!chartDom) return

      this.top10Chart = echarts.init(chartDom)
      this.updateTop10Chart();
    },

    // 更新TOP10图表
    updateTop10Chart() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e4e7ed',
          borderRadius: 8,
          boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)'
        },
        grid: {
          left: '10%',
          right: '4%',
          bottom: '3%',
          top: '0%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f0f2f5',
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: this.operatorTop10.map(item => item.name).reverse(),
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            fontSize: 10,
            color: '#606266'
          }
        },
        series: [{
          name: '调用次数',
          type: 'bar',
          data: this.operatorTop10.map(item => item.count).reverse(),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              {offset: 0, color: '#4CAF50'},
              {offset: 1, color: '#81C784'}
            ]),
            borderRadius: [0, 4, 4, 0]
          },
          // 在柱状图上方显示调用次数
          label: {
            show: true,
            position: 'right',
            color: '#606266',
            fontSize: 10,
            formatter: '{c}'
          }
        }]
      }

      this.top10Chart.setOption(option)
    },
    // 判断文本是否溢出并需要滚动
    isTextOverflow(text) {
      // 这里简化处理，实际应该通过DOM测量来判断
      // 这里假设超过20个字符的文本需要滚动
      return text && text.length > 20;
    },
    // 处理窗口大小变化
    handleResize() {
      // 使用防抖处理，避免频繁触发
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer)
      }
      this.resizeTimer = setTimeout(() => {
        this.resizeCharts()
      }, 100)
    },
    // 调整所有图表大小
      resizeCharts() {
        if (this.trendChart) {
          this.trendChart.resize()
        }
        if (this.distributionChart) {
          this.distributionChart.resize()
        }
        if (this.top10Chart) {
          this.top10Chart.resize()
        }
      },
      // 根据时间范围获取对应的日期和数据
      getTimeRangeData() {
        const currentYear = new Date().getFullYear()

        // 根据时间范围返回默认的日期和数据
          const days = parseInt(this.timeRange) || 7;
          const dates = [];
          const values = [];

          for (let i = days - 1; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            dates.push(`${month}/${day}`);
            // 生成一些模拟数据
            values.push(Math.floor(Math.random() * 100) + 150);
          }

          return { dates, values };
      },

      // 将短日期格式转换为完整日期格式
      getFullDateByShortDate(shortDate) {
        // 处理 MM/DD 格式
        if (shortDate.includes('/')) {
          const parts = shortDate.split('/')
          if (parts.length === 2) {
            // MM/DD 格式，添加当前年份
            const currentYear = new Date().getFullYear()
            return `${currentYear}年${parseInt(parts[0])}月${parseInt(parts[1])}日`
          } else if (parts.length === 3) {
            // 兼容旧的 YYYY/MM/DD 格式
            return `${parseInt(parts[0])}年${parseInt(parts[1])}月${parseInt(parts[2])}日`
          }
        }
        // 处理 MM-DD 格式（后端返回的格式）
        else if (shortDate.includes('-')) {
          const parts = shortDate.split('-')
          if (parts.length === 2) {
            // MM-DD 格式，添加当前年份
            const currentYear = new Date().getFullYear()
            return `${currentYear}年${parseInt(parts[0])}月${parseInt(parts[1])}日`
          } else if (parts.length === 3) {
            // 兼容 YYYY-MM-DD 格式
            return `${parseInt(parts[0])}年${parseInt(parts[1])}月${parseInt(parts[2])}日`
          }
        }
        return shortDate
      },

      // 切换时间范围时更新图表数据
      handleTimeRangeChange() {
        // 重新加载统计数据，使用新的时间范围
        this.loadDashboardStats();
      }
  }
}

</script>

<style lang="scss" scoped>
// 页面容器样式

// 统计卡片样式
.stat-card {
  flex: 1;
  padding: 20px;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-right: 15px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  overflow: hidden;

  &:last-child {
    margin-right: 0;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  }

  // 卡片背景装饰
  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 120px;
    height: 120px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    transform: translate(30%, -30%);
  }

  .stat-label {
    font-size: 14px;
    opacity: 0.9;
    z-index: 1;
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    margin-top: 8px;
    z-index: 1;
  }

  .stat-icon {
    position: absolute;
    bottom: 10px;
    right: 15px;
    font-size: 24px;
    opacity: 0.3;
  }
}

// 不同颜色的统计卡片
.stat-card-1 {
  background: linear-gradient(135deg, #673AB7 0%, #512DA8 100%);
}

.stat-card-2 {
  background: linear-gradient(135deg, #009688 0%, #00796B 100%);
}

.stat-card-3 {
  background: linear-gradient(135deg, #1976D2 0%, #1565C0 100%);
}

// 图表卡片样式
.chart-card {
  padding: 10px 20px 20px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
}

// 表格卡片样式
.table-card {
  padding: 0 20px 20px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
}

// 卡片头部样式
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-top: 5px;
}

// 卡片标题样式
.card-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

// 图表容器样式
.chart-container {
  flex: 1;
  height: calc(100% - 45px);
}

// 响应式图表容器样式
.chart-container-responsive {
  flex: 1;
  width: 100%;
  min-height: 250px; // 增加最小高度以确保饼图有足够空间显示标签
  position: relative;
  padding: 10px;
}

.chart-container-responsive > div {
  width: 100%;
  height: 100%;
  min-height: inherit;
}

// 饼图容器特殊样式
#distributionChart {
  width: 100%;
  height: 100%;
}

// 调整表格样式
::v-deep .el-table {
  border-radius: 8px;
  overflow: hidden;
}

::v-deep .el-table__header-wrapper {
  border-radius: 8px 8px 0 0;
}

::v-deep .el-table__body-wrapper {
  border-radius: 0 0 8px 8px;
  overflow-x: hidden;
  overflow-y: auto !important;

  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;

    &:hover {
      background: #a8a8a8;
    }
  }
}

// 调整单选按钮样式
::v-deep .el-radio-button__inner {
  border-radius: 4px;
  padding: 6px 12px;
}

::v-deep .el-radio-button__inner:hover {
  color: #1976D2;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: #1976D2;
  border-color: #1976D2;
}

// 滚动文本样式
.scrollable-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  padding: 0 5px;
  position: relative;
  box-sizing: border-box;
}

// 滚动动画
.scroll-active {
  animation: scrollText 15s linear infinite;
  text-overflow: clip;
  overflow: visible;
  white-space: nowrap;
  display: inline-block;
  width: auto;
  min-width: 100%;
  // 确保滚动文本完全可见
  position: relative;
  z-index: 1;
}

@keyframes scrollText {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

// 为表格单元格添加必要样式
::v-deep .el-table__body-cell {
  // 允许滚动文本完全显示
  overflow: visible;
  white-space: nowrap;
  position: relative;
}

// 鼠标悬停时暂停动画
.scroll-active:hover {
  animation-play-state: paused;
  cursor: pointer;
}
</style>
